package megrez.common.core.util;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.LongSupplier;

/**
 * Snowflake ID 生成器
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
public class SnowflakeSupplier implements LongSupplier, Iterable<Long> {

    public SnowflakeSupplier() {
    }

    /** For iteration */
    private int size = 0;

    public SnowflakeSupplier(int sz) {
        size = sz;
    }

    @Override
    public Iterator<Long> iterator() {
        return new SnowflakeIterator();
    }

    @Override
    public long getAsLong() {
        return Snowflake.nextId();
    }

    class SnowflakeIterator implements Iterator<Long> {
        int count = size;

        @Override
        public boolean hasNext() {
            return count > 0;
        }

        @Override
        public Long next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            count--;
            return Long.valueOf(SnowflakeSupplier.this.getAsLong());
        }

        /**
         * Not implemented
         */
        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}
